package crew.gwt.client.widgets.util;

import java.util.Date;

import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.uibinder.client.UiConstructor;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.datepicker.client.DatePicker;

import crew.gwt.client.widgets.ClassicLabel;

public class FormatedDatePicker extends VerticalPanel {

	final private DatePicker datePicker = new DatePicker();
	final private ClassicLabel text = new ClassicLabel();
	final private String title ;
	final private DateTimeFormat formater ;
	
	public @UiConstructor FormatedDatePicker(final String title,final String pattern){
		if(pattern.isEmpty())
			formater = DateTimeFormat.getFormat("dd/MM/yyyy");
		else
			formater = DateTimeFormat.getFormat(pattern);
		this.title = title;
		
	    // Set the value in the text box when the user selects a date
	    datePicker.addValueChangeHandler(new ValueChangeHandler<Date>() {
	      public void onValueChange(ValueChangeEvent<Date> event) {
	        Date date = event.getValue();
	        String dateString = formater.format(date);
	        text.setText(title + ": " + dateString);
	      }
	    });
	    //value has to set after handler to set text
	    datePicker.setValue(new Date(), true);

	    add(text);
	    add(datePicker);
	}

	public Date getValue(){
		return datePicker.getValue();
	}
	
	public void setValue(Date date){
		datePicker.setCurrentMonth(date);
		datePicker.setValue(date,true);
	}
	
}
